package de.easywakeup.gui;

import java.io.FileInputStream;
import java.util.Locale;

import de.easywakeup.R;
import de.easywakeup.appService.BroadcastReceiverAlarm;
import de.easywakeup.appService.TimerHandler;
import de.easywakeup.data.AlarmList;
import de.easywakeup.data.Data;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

@SuppressLint( "HandlerLeak" )
public class Alert extends Activity implements TextToSpeech.OnInitListener
{

	private Data data;
	private TextToSpeech tts;
	private Button btnSpeak;
	private TextView tvCancel;
	private String message;
	private AlarmList al_temp;
	private MediaPlayer m;

	private RefreshHandler mRedrawHandler = new RefreshHandler( );

	@Override
	public void onCreate( Bundle savedInstanceState )
	{
		super.onCreate( savedInstanceState );
		setContentView( R.layout.activity_alert );
		data = Data.singleton( );
		String extraFlag = getIntent( ).getStringExtra( "AlarmName" );
		al_temp = data.getAlarmListByTime( extraFlag );
		message = getIntent( ).getStringExtra( "message" );

		btnSpeak = (Button) findViewById( R.id.btnCancel );
		tvCancel = (TextView) findViewById( R.id.alertTv );

		tvCancel.setText( message );

		// Turn on the Screen

		al_temp = TimerHandler.setTimer( this, al_temp, true, 3000 ); // All 3
		// seconds
		// a new
		// Alert
		// until
		// the
		// Button
		// is pressed
		// Consider the Checkbox about Speaking before ringing
		if( al_temp.isCheckBoxAlarmInSpeechClicked( ) )
		{
			tts = new TextToSpeech( this, this );
			speakOut( );

			// start music with a delay of 5 seconds until TextToSpeech finished
			// his speech
			if( Integer.parseInt( data.getTemperature( ) ) > 100 )
			{
				mRedrawHandler.sleep( 5000 );
			}
			else
			{
				// if the weather already reported, the TextToSpeech will say
				// the temperature. This delays the music a bit longer
				mRedrawHandler.sleep( 9000 );
			}
		}
		else
		{
			startMusic( );
		}

	}

	private void startMusic( )
	{
		if( al_temp.getChoosedSound( ) != null && al_temp.getChoosedSound( ).get( "songPath" ) != null )
		{

			// Consider that the user chooses a own sound for ringing
			String path = al_temp.getChoosedSound( ).get( "songPath" );
			m = new MediaPlayer( );
			if( !al_temp.isAlreadyPlayingMusik( ) )
				try
				{
					FileInputStream fileInputStream = new FileInputStream( path );
					m.setDataSource( fileInputStream.getFD( ) );
					fileInputStream.close( );
					m.prepare( );

					if( al_temp.getChooseNoiseOfSound( ) == 0 )
					{
						m.setVolume( 100f, 100f );
					}
					else
					{
						m.setVolume( al_temp.getChooseNoiseOfSound( ), al_temp.getChooseNoiseOfSound( ) );
					}

					m.setLooping( true );
					m.start( );
					al_temp.setAlreadyPlayingMusik( true );
				}
				catch( Exception e )
				{
					e.printStackTrace( );
				}
		}

	}

	@Override
	public void onDestroy( )
	{
		al_temp.getTimer( ).cancel( al_temp.getAlarmPendingIntent( ) );
		al_temp.setTimer( null );

		// Don't forget to shutdown!
		if( tts != null )
		{
			tts.stop( );
			tts.shutdown( );
		}
		super.onDestroy( );
	}

	class RefreshHandler extends Handler
	{
		@Override
		public void handleMessage( Message msg )
		{
			startMusic( );
		}

		public void sleep( long delayMillis )
		{
			this.removeMessages( 0 );
			sendMessageDelayed( obtainMessage( 0 ), delayMillis );
		}
	};

	@Override
	public void onInit( int status )
	{
		// TODO Auto-generated method stub

		if( status == TextToSpeech.SUCCESS )
		{

			int result = tts.setLanguage( Locale.US );

			// tts.setPitch(5); // set pitch level
			// tts.setSpeechRate(2); // set speech speed rate

			if( result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED )
			{
				Log.e( "TTS", "Language is not supported" );
			}
			else
			{
				btnSpeak.setEnabled( true );
				speakOut( );
			}

		}
		else
		{
			Log.e( "TTS", "Initilization Failed" );
		}

	}

	private void speakOut( )
	{

		tts.speak( message, TextToSpeech.QUEUE_FLUSH, null );
	}

	public void cancelAlarmListener( View v )
	{
		TimerHandler.stopAlarm( al_temp );
		BroadcastReceiverAlarm.cancelNotification( this, BroadcastReceiverAlarm.ID_NOTIFICATION );
		if( m != null )
		{
			m.stop( );
			m.release( );
		}
		Intent intent = new Intent( this, MainScreen.class );
		startActivity( intent );
	}

	/**
	 * Stop the AlarmManager of tje specific AlarmList
	 * 
	 * @param al_temp
	 *            Specific AlarmList
	 */
	public static void stopAlarm( AlarmList al_temp )
	{

		if( al_temp.getAlarmPendingIntent( ) != null )
		{
			al_temp.getTimer( ).cancel( al_temp.getAlarmPendingIntent( ) );
		}

	}

	// IF the User press the "Back Button" on the keyboard, it will cancel the
	// alarm
	@Override
	public void onBackPressed( )
	{
		cancelAlarmListener( tvCancel );

	}

	// If the User press the "Home Button", it will cancel the alarm
	@Override
	public void onStop( )
	{
		super.onStop( );
		cancelAlarmListener( tvCancel );

	}

}